//获取应用实例
var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    email:"未设置",
    userData:{},
    sex:false
  },
  cancel:function(){
    wx.navigateBack({
      delta:1
    })
  },
  confirm:function(){
    wx.navigateBack({
      delta: 1
    })
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1000
    })
  },
  //初始完善资料
  perfectData:function(){
    var that = this;
    util.request(api.PerfectDataUrl, { unionid: app.globalData.unionid }).then(function(res){
      if(res.data.code == 200){
        that.setData({
          userData: res.data.data
        })
      }
      var value = res.data.data.gender
      if (value === 1) {
        that.setData({
          sex: true
        })
      }
    })

  },

  //点击保存用户资料
  listenFormSubmit: function (e) {
    var flag = true;  //判断信息输入是否完整
    var warn='';
    //判断各个输入框是否正确
    if (e.detail.value.username == "") {
      warn = "请填写您的姓名！"      
    } else if (e.detail.value.gender == "0") {
      warn = "请选择您的性别！"      
    }else if (e.detail.value.userphone == "") {
      warn = "请填写您的手机号！"           //13484827713
    } else if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(e.detail.value.userphone))) {
      warn = "手机号格式不正确！"     
    }else {
      flag = false; //若必要信息都填写，则不用弹框，且页面可以进行跳转
      var true_name = e.detail.value.username;
      var mobile = e.detail.value.userphone;
      var gender = e.detail.value.gender;
      let that = this;
      util.request(api.updateUserUrl,{
        'true_name': true_name,
        'gender': gender,
        'mobile': mobile,
        'unionid': app.globalData.unionid
      },'POST').then(function(res){
        wx.navigateBack({
          delta: 1
        })
        wx.setStorage({
          key: 'gender',
          data: '2',
        })
      })

    }
    /*如果信息填写不完整，弹出输入框*/
    if (flag == true) {
      wx.showModal({
        title: '提示',
        content: warn
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.perfectData();

    //获取用户信息,如果有则获取，没有则调用
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
  }
  
})